package linc.cool.lock;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author yqlin
 * @date 2021/12/28 1:00 AM
 * @description
 */
@Slf4j
public class ReentrantLockDemo {
    private static int sum = 0;
    private static final ReentrantLock reentrantLock = new ReentrantLock();

    public static void main(String[] args) throws InterruptedException {
        for (int i = 0; i < 3; i++) {
            Thread thread = new Thread(() -> {
                // 加锁
                reentrantLock.lock();
                try {
                    // 临界区代码
                    for (int j = 0; j < 10000; j++) {
                        sum++;
                    }
                } finally {
                    reentrantLock.unlock();
                }
            });
            thread.start();
        }
        TimeUnit.SECONDS.sleep(2);
        log.debug("sum: {}", sum);
    }
}
